<template>
  
  <div class="app-container">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="left-tools">
        <el-button type="primary" @click="handleSaveAndAdd">保存并新增</el-button>
        <el-button @click="handleSave">保存</el-button>
        
        <el-dropdown>
          <el-button>
            打印
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>打印选项1</el-dropdown-item>
              <el-dropdown-item>打印选项2</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="right-tools">
        <el-button-group>
          <el-button>上一页</el-button>
          <el-button>下一页</el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 凭证主体 -->
    <div class="voucher-container">
      <!-- 凭证头部 -->
      <div class="voucher-header">
        <div class="header-item">
          <el-select v-model="voucherForm.word" placeholder="记" style="width: 80px">
            <el-option label="记" value="记" />
            <el-option label="收" value="收" />
            <el-option label="付" value="付" />
            <el-option label="转" value="转" />
          </el-select>
          <el-input v-model="voucherForm.number" style="width: 60px" placeholder="2" />
          <span class="label">号</span>
        </div>
        <div class="header-item">
          <span class="label">日期：</span>
          <el-date-picker
            v-model="voucherForm.voucherDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width: 150px"
          />
        </div>
        <div class="header-item">
          <span class="label">附单据</span>
          <el-input v-model="voucherForm.attachment" style="width: 60px" />
          <span class="label">张</span>
        </div>
      </div>

      <!-- 凭证表格 -->
        <el-button type="primary" @click="addEmptyRow()">新增</el-button>
      <el-table 
        :data="voucherForm.details" 
        border 
        style="width: 100%"
        :cell-style="{ padding: '5px 0' }"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column label="序号" width="60" align="center">
          <template #default="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="摘要" width="300">
          <template #default="scope">
            <el-select
              v-model="scope.row.summary"
              filterable
              allow-create
              default-first-option
              placeholder="请输入或选择摘要"
              style="width: 100%"
              @change="handleSummaryChange"
            >
              <el-option
                v-for="item in defaultSummaries.concat(tempSummaries)"
                :key="item.value || item"
                :label="item.label || item"
                :value="item.value || item"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="会计科目">
          <template #default="scope">
            <el-select
              v-model="scope.row.subject_id"
              filterable
              placeholder="请选择科目"
              style="width: 100%"
              :loading="loading"
              @change="(value) => handleSubjectChange(value, scope.row)"
            >
              <el-option
                v-for="item in subjectOptions "
                :key="item.id"
                :label="item.subjectName"
                :value="item.id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="借方金额" width="200">
          <template #header>
            <div class="amount-header">
              <span v-for="(unit, index) in moneyUnits" :key="index">{{ unit }}</span>
            </div>
          </template>
          <template #default="scope">
            <el-input
              v-model="scope.row.debitAmount"
              placeholder="0.00"
              :bordered="false"

            />
            
          </template>
        </el-table-column>
        <el-table-column label="贷方金额" width="200">
          <template #header>
            <div class="amount-header">
              <span v-for="(unit, index) in moneyUnits" :key="index">{{ unit }}</span>
            </div>
          </template>
          <template #default="scope">
           
            <el-input
              v-model="scope.row.creditAmount"
              placeholder="0.00"
              :bordered="false"
              
            />
          </template>
        </el-table-column>

         <el-table-column label="操作" width="200">
          
          <template #default="scope">
            <el-button type="danger" @click="deleteRow(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 合计行 -->
      <div class="total-row">
        <span>合计：零元整</span>
        <div class="amount-total">
          <span>借方：{{ totalDebit.toFixed(2) }}</span>
          <span>贷方：{{ totalCredit.toFixed(2) }}</span>
        </div>
      </div>

      <!-- 制单人信息 -->
      <div class="voucher-footer">
        <span>制单人：会计007</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { addVoucher, listDetails } from "@/api/system/voucher"

const router = useRouter()

// 金额单位
const moneyUnits = ['亿', '千', '百', '十', '万', '千', '百', '十', '元', '角', '分']

// 默认的摘要选项（固定不变）
const defaultSummaries = [
  '提现',
  '利息收入',
  '支付银行手续费',
  '报销销售人员的业务招待费',
  '购入固定资产',
  '支付货款',
  '销售',
  '收货款'
]

// 临时摘要选项（当前会话新增的）
const tempSummaries = ref([])

// 处理摘要变化
const handleSummaryChange = (value) => {
  if (!value) return
  console.log('选中的值:', value)
  console.log('当前行数据:', scope.row)
  
  if (!defaultSummaries.includes(value) && !tempSummaries.value.includes(value)) {
    tempSummaries.value.unshift(value)
    ElMessage.success('已添加到常用摘要')
  }
}

// 科目选项列表
const subjectOptions = ref([])
const loading = ref(false)

// 表单数据
const voucherForm = reactive({
  word: '记',
  number: '2',
  voucherDate: new Date().toISOString().split('T')[0],
  attachment: 0,
  details: [
    {
      summary: '',
      subject_id: '',
      subject_name: '',
      debitAmount: '',
      creditAmount: ''
    }
  ]
})

// 计算借贷方合计
const totalDebit = computed(() => {
  return voucherForm.details.reduce((sum, item) => {
    return sum + (Number(item.debitAmount) || 0)
  }, 0)
})

const totalCredit = computed(() => {
  return voucherForm.details.reduce((sum, item) => {
    return sum + (Number(item.creditAmount) || 0)
  }, 0)
})

// 添加空行
const addEmptyRow = () => {
  voucherForm.details.push({
    summary: '',
    subject_id: '',
    subject_name: '',
    debitAmount: null,
    creditAmount: null
  })
}

const deleteRow = (index) => {
  voucherForm.details.splice(index, 1)
}

// 计算合计
const calculateTotal = () => {
  // 自动添加新行
  if (voucherForm.details[voucherForm.details.length - 1].summary || 
      voucherForm.details[voucherForm.details.length - 1].subject_id ||
      voucherForm.details[voucherForm.details.length - 1].debitAmount ||
      voucherForm.details[voucherForm.details.length - 1].creditAmount) {
    addEmptyRow()
  }
}

// 返回列表页
const goBack = () => {
  router.push('/system/voucher')
}

// 保存
const handleSave = async () => {
  try {
    // 校验借贷是否平衡
    if (totalDebit.value !== totalCredit.value) {
      ElMessage.error('借贷不平衡！')
      return
    }
    
    // 校验必填项
    if (!voucherForm.voucherDate) {
      ElMessage.error('请选择凭证日期！')
      return
    }

    // 过滤掉空行并格式化数据
    const validDetails = voucherForm.details.filter(detail => 
      detail.summary || 
      detail.subject_id || 
      detail.debitAmount || 
      detail.creditAmount
    )

    if (validDetails.length === 0) {
      ElMessage.error('请填写凭证明细！')
      return
    }

    // 构造请求数据 - 转换为后端需要的格式
    const voucherList = validDetails.map(detail => ({
      id: null,
      word: voucherForm.word,
      code: 0,
      remark: detail.summary,
      subjectName: detail.subject_name,
      receiptNum: 0,
      createMember: 0,
      debitAmount: Number(detail.debitAmount) || 0,
      creditAmount: Number(detail.creditAmount) || 0,
      accountSetsId: Number(detail.subject_id) || 0,
      voucherYear: new Date(voucherForm.voucherDate).getFullYear(),
      voucherMonth: new Date(voucherForm.voucherDate).getMonth() + 1,
      voucherDate: voucherForm.voucherDate,
      auditMemberId: 0,
      auditMemberName: null,
      carryForward: 0
    }))

    console.log('发送的数据:', voucherList) // 添加日志
    await addVoucher(voucherList)
    ElMessage.success('保存成功')
    goBack()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 保存并新增
const handleSaveAndAdd = async () => {
  try {
    // 校验借贷是否平衡
    if (totalDebit.value !== totalCredit.value) {
      ElMessage.error('借贷不平衡！')
      return
    }
    
    // 校验必填项
    if (!voucherForm.voucherDate) {
      ElMessage.error('请选择凭证日期！')
      return
    }

    // 过滤掉空行并格式化数据
    const validDetails = voucherForm.details.filter(detail => 
      detail.summary || 
      detail.subject_id || 
      detail.debitAmount || 
      detail.creditAmount
    )

    if (validDetails.length === 0) {
      ElMessage.error('请填写凭证明细！')
      return
    }

    // 构造请求数据 - 转换为后端需要的格式
    const voucherList = validDetails.map(detail => ({
      id: null,
      word: voucherForm.word,
      code: 0,
      remark: detail.summary,
      subjectName: detail.subject_name,
      receiptNum: 0,
      createMember: 0,
      debitAmount: Number(detail.debitAmount) || 0,
      creditAmount: Number(detail.creditAmount) || 0,
      accountSetsId: Number(detail.subject_id) || 0,
      voucherYear: new Date(voucherForm.voucherDate).getFullYear(),
      voucherMonth: new Date(voucherForm.voucherDate).getMonth() + 1,
      voucherDate: voucherForm.voucherDate,
      auditMemberId: 0,
      auditMemberName: null,
      carryForward: 0
    }))

    await addVoucher(voucherList)
    ElMessage.success('保存成功')
    
    // 重置表单
    voucherForm.details = [{
      summary: '',
      subject_id: '',
      subject_name: '',
      debitAmount: null,
      creditAmount: null
    }]
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 获取科目列表
const listDetail = async () => {
 const res = await listDetails()
    console.log('科目列表原始数据:', res)
    subjectOptions.value = res.data;
    console.log('科目列表数据:', subjectOptions.value)

}

// 确保组件卸载时清理数据
onUnmounted(() => {
  subjectOptions.value = []
})

// 监听数据变化
watch(subjectOptions, (newVal) => {
  console.log('科目列表数据变化:', newVal)
}, { deep: true })

watch(() => voucherForm.details, (newVal) => {
  console.log('凭证明细更新:', newVal)
}, { deep: true })

onMounted(() => {
  listDetail(); // 页面加载时获取科目列表 
})

// 处理科目选择变化
const handleSubjectChange = (value, row) => {
  const selected = subjectOptions.value.find(item => item.value === value)
  if (selected) {
    row.subject_id = selected.subject_id
    row.subject_name = selected.subject_name
    console.log('选中科目:', selected)
    console.log('更新后的行数据:', row)
  }
}

</script>

<style scoped>  
.app-container {
  padding: 20px;
  background-color: #fff;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.left-tools {
  display: flex;
  gap: 10px;
}

.voucher-container {
  border: 1px solid #dcdfe6;
  padding: 20px;
}

.voucher-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.label {
  font-size: 14px;
  color: #606266;
}

.amount-header {
  display: flex;
  justify-content: space-around;
}

.total-row {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #dcdfe6;
  margin: 10px 0;
}

.amount-total {
  display: flex;
  gap: 20px;
}

.voucher-footer {
  margin-top: 20px;
  color: #606266;
  font-size: 14px;
}

:deep(.el-input__wrapper) {
  box-shadow: none;
}

:deep(.el-input__inner) {
  text-align: center;
}

/* 下拉框样式优化 */
:deep(.el-select .el-input__wrapper) {
  box-shadow: none;
  padding: 0 8px;
}

:deep(.el-select-dropdown__item) {
  padding: 8px 12px;
  font-size: 14px;
}

:deep(.el-select .el-input__inner) {
  border: none;
  padding: 0;
}

:deep(.el-select .el-input.is-focus .el-input__wrapper) {
  box-shadow: none;
}
</style> 